package com.wty.shop.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author 34355
 * @Create 2018-01-29-22:47
 */
@Slf4j
public class CookieUtil {
    private static final String COOKIE_DOMAIN=".wty.com";
    private static final String COOKIE_NAME="mmall_login_token";

    /**
     * 写cookie
     * @param response
     * @param token
     */
    public static void writeLoginToken(HttpServletResponse response, String token){
        Cookie ck=new Cookie(COOKIE_NAME,token);
        ck.setDomain(COOKIE_DOMAIN);
        ck.setPath("/");//代表设置在根目录
        //防止脚本来访问进行操作
        ck.setHttpOnly(true);
        //如果这个maxage不设置的话，cookie就不会写入硬盘，而是写在内存。只在当前页面有效
        //这是为-1 永久 设置为0 立马死去
        ck.setMaxAge(60*60*24*365);
        log.info("write cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());
        response.addCookie(ck);
    }

    /**
     * 读登陆token
     * @param request
     * @return
     */
    public static String readLoginToken(HttpServletRequest request){
        Cookie[] cks=request.getCookies();
        if(cks!=null){
            for(Cookie ck:cks){
                log.info("read cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());
                if (StringUtils.equals(ck.getName(),COOKIE_NAME)){
                    log.info("return cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());
                    return ck.getValue();
                }
            }
        }
        return null;
    }

    public static void delLoginToken(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cks=request.getCookies();
        if(cks!=null){
            for(Cookie ck:cks){
                if (StringUtils.equals(ck.getName(),COOKIE_NAME)){
                    ck.setDomain(COOKIE_DOMAIN);
                    ck.setPath("/");
                    ck.setMaxAge(0);
                    log.info("del cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());
                    response.addCookie(ck);
                    return;//如果删除了就终止这个循环了
                }
            }
        }
    }
}
